package com.ikangtai.shecare.main;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ikangtai.shecare.R;
import com.ikangtai.shecare.common.App;
import com.ikangtai.shecare.common.eventBusMsg.NickNameMsg;
import com.ikangtai.shecare.common.eventBusMsg.WebviewInitDataMsg;
import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.common.util.AvatarImageMsg;
import com.ikangtai.shecare.common.util.FileUtil;
import com.ikangtai.shecare.personal.AboutActivity;
import com.ikangtai.shecare.personal.CollectionActivity;
import com.ikangtai.shecare.personal.HelpCenterActivity;
import com.ikangtai.shecare.personal.MyDeviceActivity;
import com.ikangtai.shecare.personal.MyInfoActivity;
import com.ikangtai.shecare.personal.SettingsActivity;
import com.ikangtai.shecare.personal.StateActivity;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subcriber;

import java.io.File;


/**
 * A simple {@link Fragment} subclass.
 */
public class PersonalFragment extends Fragment implements View.OnClickListener {
    private TextView userName;
    private Button btn_personal_state;
    private Button btn_myInfo;
    private Button btn_shopping;
    private Button btn_myDevice;
    private Button personal_collection_btn;
    private final String SHOPPING_URL = "http://www.ikangtai.com/phone_car.html";
    private LinearLayout helpCenterLinearLayout;
    private LinearLayout aboutLinearLayout;
    private LinearLayout updateLinearLayout;
    private Button myInfoButton;
    private Button myDeviceButton;
    private ImageView profileImage;
    private TextView nickNameTextView;
    private static final int SAVE_NICK_NAME_OK = 1;
    private static final int RESULT_UPDATE_STATUS_CODE = 1;
    private static final int RESULT_UPDATE_PHOTO_CODE = 2;
    private FileUtil fileUtil = new FileUtil();

    public PersonalFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        long t1 = System.currentTimeMillis();
        AppLog.i("get in PersonalFragment start!");

        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_personal, container, false);

        view.findViewById(R.id.setButton).setOnClickListener(this);
        EventBus.getDefault().register(this);
        initView(view);
//        StatusBarUtil.setColor(getActivity(), getResources().getColor(R.color.orange), 0);
        long t2 = System.currentTimeMillis();
        AppLog.i("get in PersonalFragment end! time = " + (t2 - t1));

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        AppLog.i("LifeCycle get in PersonalFragment onResume!");
    }

    private void initView(View view) {
        nickNameTextView = (TextView) view.findViewById(R.id.nickNameTextView);
        String nickName = App.memory_preference_nickName;
        nickName = (nickName == null) ? this.getString(R.string.user_nickname) : nickName;
        nickNameTextView.setText(nickName);

        userName = (TextView) view.findViewById(R.id.userName);
        userName.setText(App.userName);

        btn_myInfo = (Button) view.findViewById(R.id.myInfo);
        btn_myInfo.setOnClickListener(personalOnClickListener);

        btn_shopping = (Button) view.findViewById(R.id.btn_shopping);
        btn_shopping.setOnClickListener(personalOnClickListener);

        btn_myDevice = (Button) view.findViewById(R.id.myDevice);
        btn_myDevice.setOnClickListener(personalOnClickListener);

        btn_personal_state = (Button) view.findViewById(R.id.personal_state_btn);

        btn_personal_state.setText(App.getStatus(App.status));
        btn_personal_state.setOnClickListener(personalOnClickListener);

        helpCenterLinearLayout = (LinearLayout) view.findViewById(R.id.personal_list_helpCenter);
        helpCenterLinearLayout.setOnClickListener(personalOnClickListener);

        aboutLinearLayout = (LinearLayout) view.findViewById(R.id.personal_list_about);
        aboutLinearLayout.setOnClickListener(personalOnClickListener);

        updateLinearLayout = (LinearLayout) view.findViewById(R.id.personal_list_update);
        updateLinearLayout.setOnClickListener(personalOnClickListener);

        profileImage = (ImageView) view.findViewById(R.id.profile_image);

        if (fileUtil.existSDCard()) {
            showAvatarImage();
        } else {
            Toast.makeText(getContext(), R.string.inster_sd, Toast.LENGTH_SHORT).show();
        }

        view.findViewById(R.id.personal_collection_btn).setOnClickListener(personalOnClickListener);
        view.findViewById(R.id.profile_image).setOnClickListener(personalOnClickListener);

    }

    private void showAvatarImage() {
        /*显示头像图片*/
        String avatarName = App.userName + "_avatar.jpg";
        String externalCacheDir = this.getActivity().getExternalCacheDir().getAbsolutePath() + "/";
        String avatarPath = externalCacheDir + avatarName;

        Bitmap bitmap = null;
        File file = new File(avatarPath);
        if (file.exists()) {
            bitmap = BitmapFactory.decodeFile(avatarPath);
        }
        if (!(bitmap == null)) {
            profileImage.setImageBitmap(bitmap);
        }
    }

    private View.OnClickListener personalOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.myInfo:
                    Intent myInfoIntent = new Intent(getActivity(), MyInfoActivity.class);
                    startActivityForResult(myInfoIntent, 0);
                    break;
                case R.id.btn_shopping:
                    Uri shoppingUri = Uri.parse(SHOPPING_URL);
                    Intent shoppingIntent = new Intent(Intent.ACTION_VIEW, shoppingUri);
                    startActivity(shoppingIntent);
                    break;
                case R.id.myDevice:
                    Intent myDeviceIntent = new Intent(getActivity(), MyDeviceActivity.class);
                    startActivity(myDeviceIntent);
                    break;
                case R.id.personal_state_btn:
                    Intent personal_state_intent = new Intent(getActivity(), StateActivity.class);
                    personal_state_intent.putExtra("personalChange", 1);
                    startActivityForResult(personal_state_intent, 0);
                    break;
                case R.id.personal_list_helpCenter:
                    Intent helpCenterIntent = new Intent(getActivity(), HelpCenterActivity.class);
                    startActivity(helpCenterIntent);
                    break;
                case R.id.personal_list_about:
                    Intent aboutIntent = new Intent(getActivity(), AboutActivity.class);
                    startActivity(aboutIntent);
                    break;
                case R.id.personal_collection_btn:
                    Intent collectionIntent = new Intent(getActivity(), CollectionActivity.class);
                    startActivity(collectionIntent);
                    break;
                case R.id.profile_image:
                    Intent profileImageIntent = new Intent(getActivity(), MyInfoActivity.class);
                    startActivityForResult(profileImageIntent, 0);
                    break;
                case R.id.personal_list_update:
                    break;
            }
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case RESULT_UPDATE_STATUS_CODE:
                int personal_state = data.getIntExtra("personal_state", App.STATUS_BEIYUN);
                String personal_state_str = App.getStatus(personal_state);
                AppLog.i("personal_state_str=" + personal_state_str);
                btn_personal_state.setText(personal_state_str);
                EventBus.getDefault().post(new WebviewInitDataMsg());
                break;
            case RESULT_UPDATE_PHOTO_CODE:
                if (fileUtil.existSDCard()) {
                    showAvatarImage();
                } else {
                    Toast.makeText(getContext(), R.string.inster_sd, Toast.LENGTH_SHORT).show();
                }
                AppLog.i("set profile image.");
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.setButton:
                Intent setIntent = new Intent(getContext(), SettingsActivity.class);
                startActivity(setIntent);
                break;
        }
    }

    @Subcriber
    private void getNickNameEventBusMsg(NickNameMsg nickNameMsg) {
        int eventBusCode = nickNameMsg.getRespCode();
        switch (eventBusCode) {
            case SAVE_NICK_NAME_OK:
                nickNameTextView.setText(nickNameMsg.getNickName());
                App.memory_preference_nickName = nickNameMsg.getNickName();
                break;
        }
    }

    /**
     * 设置头像
     *
     * @param avatarImageMsg
     */
    @Subcriber
    private void getAvatarImageMsg(AvatarImageMsg avatarImageMsg) {
        int eventBusCode = avatarImageMsg.getRespCode();
        switch (eventBusCode) {
            case RESULT_UPDATE_PHOTO_CODE:
                if (fileUtil.existSDCard()) {
                    showAvatarImage();
                } else {
                    Toast.makeText(getContext(), R.string.inster_sd, Toast.LENGTH_SHORT).show();
                }
                AppLog.i("set profile image.");
                break;
        }
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

    }
}
